<!-- 心理测评表 -->
<template>
  <div class="heartMark">
    <!-- 模糊查询 -->
    <el-input
      placeholder="请输入内容"
      v-model="blurredName"
      style="width: 300px; margin-left: 50px"
    ></el-input>
    <el-button type="primary" @click="selectBlurred" style="margin-right: 20px"
      >查询</el-button
    >
    <!-- 添加按钮 -->
    <el-button
      type="primary"
      @click="dialogFormVisible = true"
      style="margin-right: 400px; float: right"
      >新增</el-button
    >
    <el-dialog title="新增测评信息" :visible.sync="dialogFormVisible">
      <el-form :model="add">
        <el-form-item label="测评名称" :label-width="formLabelWidth">
          <el-input v-model="add.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input v-model="add.simplyintroduce" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/heartmark/fileup"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            style="width: 150px; height: 150px"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="题目数量" :label-width="formLabelWidth">
          <el-input v-model="add.total" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="发布用户"
          prop="userId"
          :label-width="formLabelWidth"
        >
          <el-select v-model="add.userId" placeholder="请选择">
            <el-option
              v-for="item in this.UsersId"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearAdd">取 消</el-button>
        <el-button type="primary" @click="insertHeartMark">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 表格显示区域 -->
    <el-table :data="heartMarks" style="width: 100%">
      <el-table-column prop="id" label="id" width="80" align="center">
      </el-table-column>
      <el-table-column prop="name" label="测评名" width="180" align="center">
      </el-table-column>
      <el-table-column prop="picture" label="图片" width="120" align="center">
        <template slot-scope="scope">
          <div class="img-container" @click="showImage(scope.row.picture)">
            <img :src="scope.row.picture" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="simplyintroduce" label="简介" align="center">
      </el-table-column>
      <el-table-column prop="total" label="题目数量" width="120" align="center">
      </el-table-column>
      <el-table-column prop="userId" label="用户ID" width="120" align="center">
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button
            @click="handleDelete(scope.row)"
            type="danger"
            icon="el-icon-delete"
            size="small"
            >删除</el-button
          >
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="small"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑 -->
    <el-dialog title="编辑测评信息" :visible.sync="isEdit">
      <el-form :model="edit">
        <el-form-item label="测评名称" :label-width="formLabelWidth">
          <el-input v-model="edit.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input
            v-model="edit.simplyintroduce"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/heartmark/fileup"
            :show-file-list="false"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload2"
            style="width: 150px; height: 150px"
          >
            <img v-if="edit.picture" :src="edit.picture" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="题目数量" :label-width="formLabelWidth">
          <el-input v-model="edit.total" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="发布用户"
          prop="userId"
          :label-width="formLabelWidth"
        >
          <el-select v-model="edit.userId" placeholder="请选择">
            <el-option
              v-for="item in this.UsersId"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEdit = false">取 消</el-button>
        <el-button type="primary" @click="updateHeartMark">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 模态框（点击图片方法效果） -->
    <el-dialog :visible.sync="dialogVisible" width="30%">
      <img :src="dialogImageUrl" alt="大图" style="width: 100%" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[5, 10, 30, 50]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: "HeartMarkComponent",
  data() {
    //这里存放数据
    return {
      page: 1, //当前页码
      size: 10, //每页显示条数
      heartMarks: [], //表格数据
      totalCount: 0, //总条数
      dialogVisible: false, //模态框是否显示
      dialogImageUrl: "", //放大图片的图片地址
      dialogFormVisible: false, //表单是否显示
      isEdit: false, //是否显示编辑表单
      add: {
        //新增的表单数据
        id: "", //id
        name: "", //测评名
        simplyintroduce: "", //简介
        picture: "", //图片
        total: "", //题目数量
        userId: "", //用户id
      },
      edit: {},
      formLabelWidth: "120px",
      UsersId: [], //新增时下拉列表用户name
      imageUrl: "", //回显图片地址
      blurredName: "", //模糊查询名称
    };
  },
  //方法集合
  methods: {
    //模糊查询
    selectBlurred() {
      console.log("模糊查询", this.blurredName);
      this.axios({
        url: "http://localhost:8080/heartmark/findHeartMarkByName",
        method: "get",
        params: {
          name: this.blurredName,
          page: this.page,
          size: this.size,
        },
      }).then((res) => {
        this.heartMarks = res.data.data.list;
        this.totalCount = res.data.data.total;
      });
    },

    //修改点击提交
    updateHeartMark() {
      this.isEdit = false;
      console.log("edit", this.edit);

      this.axios
        .put("http://localhost:8080/heartmark/updateHeartMark", this.edit)
        .then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
            this.selectAllHeartMark();
          } else {
            this.$message.error("修改失败!");
          }
        });
    },

    //点击修改，数据回显
    handleEdit(row) {
      (this.isEdit = true), console.log(row);
      this.axios
        .get("http://localhost:8080/heartmark/findHeartMarkById?id=" + row.id)
        .then((res) => {
          this.edit = res.data.data.data;
          console.log(res);
        });
    },

    // 新增返回图片的地址
    handleAvatarSuccess(res, file) {
      this.add.picture =
        "http://localhost:8080/heartmark/downImg?file=" + file.response.data;
    },

    beforeAvatarUpload(file) {
      this.imageUrl = URL.createObjectURL(file);
    },

    // 修改返回图片的地址
    handleAvatarSuccess2(res, file) {
      this.edit.picture =
        "http://localhost:8080/heartmark/downImg?file=" + file.response.data;
    },

    beforeAvatarUpload2(file) {
      this.edit.picture = URL.createObjectURL(file);
    },

    //新增
    insertHeartMark() {
      (this.dialogFormVisible = false), console.log(this.add);
      this.axios({
        url: "http://localhost:8080/heartmark/addHeartMark",
        method: "post",
        data: JSON.stringify(this.add),
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
        },
      })
        .then((res) => {
          console.log(res);
          this.clearAdd();
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //点击取消新增的数据清除
    clearAdd() {
      this.dialogFormVisible = false;
      (this.add = {
        //新增的表单数据
        id: "", //id
        name: "", //测评名
        simplyintroduce: "", //简介
        picture: "", //图片
        total: "", //题目数量
        userId: "", //用户id
      }),
        (this.imageUrl = ""); //回显图片地址
    },

    //查询所有数据
    selectAllHeartMark() {
      this.axios({
        url: "http://localhost:8080/heartmark/findAllHeartMark",
        method: "get",
        params: {
          page: this.page,
          size: this.size,
        },
      })
        .then((res) => {
          console.log(res);
          this.heartMarks = res.data.data.list;
          this.totalCount = res.data.data.total;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 分页
    handleSizeChange(size) {
      this.size = size;

      if ((this.name = null)) {
        this.page = 1; // 重置为第一页
        this.selectAllHeartMark();
      } else {
        this.selectBlurred();
      }
    },

    // 页码改变
    handleCurrentChange(page) {
      this.page = page;
      if ((this.name = null)) {
        this.selectAllHeartMark();
      } else {
        this.selectBlurred();
      }
    },
    //点击图片,显示大图效果
    showImage(imageUrl) {
      console.log("Image clicked:", imageUrl);
      this.dialogImageUrl = imageUrl;
      this.dialogVisible = true; // 打开模态框
    },

    //确认删除的弹框
    handleDelete(row) {
      this.$confirm("确认删除这条知识记录吗？", "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.handleClick(row);
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },

    // 删除
    handleClick(row) {
      this.axios({
        url: `http://localhost:8080/heartmark/deleteHeartMarkById/` + row.id,
        method: "delete",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + localStorage.getItem("token"), // 如果需要认证
          "Custom-Header": "Some-Value", // 任何其他自定义头部
        },
      }).then((res) => {
        console.log(res);
        this.selectAllHeartMark();
      });
    },

    //查询user表数据
    selectUserIdAndname() {
      this.axios({
        url: "http://localhost:8080/heartmark/selectAllUserById",
        method: "get",
      })
        .then((res) => {
          this.UsersId = res.data.data.data;
          console.log("user表", res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },

  mounted() {
    this.selectAllHeartMark();
    this.selectUserIdAndname();
  },
};
</script>
<style scoped>
.img-container {
  width: 70px;
  height: 70px;
  position: relative;
  border-radius: 20%;
}

.img-container > img {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  object-fit: cover;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 20%;
}

.play-icon {
  font-size: 30px;
  line-height: 70px;
  margin: 0 auto;
}

.avatar-uploader {
  margin-bottom: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.img-container {
  width: 100px; /* 固定宽度 */
  height: 100px; /* 固定高度 */
  position: relative;
  border-radius: 20%;
  overflow: hidden; /* 确保超出部分被隐藏 */
  cursor: pointer; /* 鼠标悬停时显示为手型 */
}

.img-container > img {
  width: 100%; /* 使图片宽度适应容器 */
  height: 100%; /* 使图片高度适应容器 */
  object-fit: cover; /* 保持图片比例并填充容器 */
}
</style>